package com.mymarkdown.app.util;


import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.mymarkdown.app.common.itext.ChineseFontProvider;

import java.io.*;

/**
 * @author zenglun
 * @date 2021/12/7 5:01 下午
 * @description: TODO
 */
public class HtmlToPdfUtil {
    private HtmlToPdfUtil() {
    }

    /**
     * 将HTML转成PD格式的文件。html文件的格式比较严格
     *
     * @param htmlPath      HTML的路径
     * @param targetPdfPath 目标转换后的pdf存储路径
     * @throws IOException 写入pdf失败抛出的异常
     */
    public static void HTMLToPdf(String htmlPath, String targetPdfPath) throws IOException {
        File htmlSource = new File(htmlPath);
        File pdfDest = new File(targetPdfPath);
        ConverterProperties converterProperties = new ConverterProperties();
        ChineseFontProvider chineseFontProvider = new ChineseFontProvider();
        converterProperties.setFontProvider(chineseFontProvider);
        HtmlConverter.convertToPdf(new FileInputStream(htmlSource),
                new FileOutputStream(pdfDest), converterProperties);
    }

    /**
     * 将HTML转成PD格式的文件。html文件的格式比较严格
     *
     * @param htmlContent   html内容
     * @param targetPdfPath 目标转换后的pdf存储路径
     * @throws IOException 写入pdf失败抛出的异常
     */
    public static void HTMLContentToPdf(String htmlContent, String targetPdfPath) throws IOException {
        File pdfDest = new File(targetPdfPath);
        ConverterProperties converterProperties = new ConverterProperties();
        ChineseFontProvider chineseFontProvider = new ChineseFontProvider();
        converterProperties.setFontProvider(chineseFontProvider);
        HtmlConverter.convertToPdf(htmlContent,
                new FileOutputStream(pdfDest), converterProperties);
    }
}
